package fun.tan90.http.plugin.config;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequiredArgsConstructor
public class VertxHttpServer extends AbstractVerticle {

    private final int port;

    private final String path;

    private final long bodyLimit;

    private HttpServer httpServer;

    @Override
    public void start(Promise<Void> startPromise) {
        // 创建 HTTP 服务器
        this.httpServer = vertx.createHttpServer();

        // 创建路由器
        Router router = Router.router(vertx);

        // 解析请求体
        router.route().handler(BodyHandler.create().setBodyLimit(bodyLimit));

        // 全局日志中间件
        router.route().handler(ctx -> {
            log.info("{} {} ", ctx.request().method(), ctx.request().path());
            ctx.next();
        });

        router.route(HttpMethod.GET, path).handler(ctx -> {
            String name = ctx.queryParam("name").get(0);
            log.info("请求参数 {}", name);
            ctx.response().end();
        });

        router.route(HttpMethod.POST, path).handler(ctx -> {
            String body = ctx.body().asString();
            log.info("请求体 {}", body);
            ctx.response().end();
        });

        // 启动服务器
        httpServer.requestHandler(router).listen(port, event -> {
            if (event.succeeded()) {
                startPromise.complete();
            } else {
                startPromise.fail(event.cause());
            }
        });
    }

    @Override
    public void stop(Promise<Void> stopPromise) {
        httpServer.close(event -> {
            if (event.succeeded()) {
                log.info("HTTP 服务器已关闭 【{}】", port);
                stopPromise.complete();
            } else {
                stopPromise.fail(event.cause());
            }
        });
    }

}